package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"order-mate/cache"
	"order-mate/model"
	"order-mate/pkg"
	"strconv"
	"time"
)

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	if id == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为0",
		})
		return
	}
	var user model.User
	redis_key := "detail" + strconv.Itoa(id)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Where("id=?", id).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	if page == 0 || size == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为0",
		})
		return
	}
	var user []model.User
	var total int64
	offset := (page - 1) * size
	redis_key := "list_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &user)
	}
	model.DB.Model(&user).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  user,
		"total": total,
	})
	return
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,已禁封",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,已禁封",
			})
			return
		} else {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误,请重新输入",
			})
			return
		}
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
